 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=42 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Reading and writing text files
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='buffer,buffering,buffers,close,flush,i/o,input/output,java.io,reader,writer,read,text,write,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Reading and writing text files</div>

<div class='main-body'>
 
<br>When reading and writing text files :
<ul>
<li>
it's almost always a good idea to use buffering (default size is 8K)</li>

<li>
it's often possible to use references to abstract base classes, instead
of references to specific concrete classes</li>

<li>
there is always a need to pay attention to exceptions (in particular, <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/IOException.html">IOException</a></tt>
and <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/FileNotFoundException.html">FileNotFoundException</a></tt>)</li>
</ul>
The <tt>close</tt> method :
<ul>
<li>
always needs to be called, or else resources will leak</li>

<li>
will automatically flush the stream, if necessary</li>

<li>
calling <tt>close</tt> on a "wrapper" stream will automatically call <tt>close</tt>
on its underlying stream</li>

<li>
closing a stream a second time has no consequence</li>
<li>when called on a <tt><a href='http://java.sun.com/javase/6/docs/api/java/util/Scanner.html'>Scanner</a></tt>, the 
<tt>close</tt> operation only works if the item passed to its constructor implements <tt><a href='http://download.oracle.com/javase/6/docs/api/java/io/Closeable.html'>Closeable</a></tt>. 
Warning: if you pass a <a href='http://download.oracle.com/javase/6/docs/api/java/io/File.html'><tt>File</tt></a> to a <tt>Scanner</tt>, you will <i>not</i> be able to close it!
Try using a  <tt>FileReader</tt> instead.
</ul>


Commonly used items :
<ul>
<li><tt><a href='http://java.sun.com/javase/6/docs/api/java/util/Scanner.html'>Scanner</a></tt> - allows 
reading files in a compact way</li>
<li><tt><a href="http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html">BufferedReader</a></tt> - <tt>readLine</tt></li>
<li>
<tt><a href="http://java.sun.com/javase/6/docs/api/java/io/BufferedWriter.html">BufferedWriter</a></tt> - <tt>write</tt>
+ <tt>newLine</tt></li>
</ul>

The <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/FileReader.html">FileReader</a></tt>
and <tt><a href="http://java.sun.com/javase/6/docs/api/java/io/FileWriter.html">FileWriter</a></tt>
classes <b>are a bit tricky, since they implicitly use the system's default character encoding</b>. If this
default is not appropriate (for example, when reading an XML file which
specifies its own encoding), the recommended alternatives are, for example :
<p><tt><a href="http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html">FileInputStream</a>
fis = new FileInputStream("test.txt");</tt>
<br><tt><a href="http://java.sun.com/javase/6/docs/api/java/io/InputStreamReader.html">InputStreamReader</a>
in = new InputStreamReader(fis, "UTF-8");</tt>
<p><tt><a href="http://java.sun.com/javase/6/docs/api/java/io/FileOutputStream.html">FileOutputStream</a>
fos = new FileOutputStream("test.txt");</tt>
<br><tt><a href="http://java.sun.com/javase/6/docs/api/java/io/OutputStreamWriter.html">OutputStreamWriter</a>
out = new OutputStreamWriter(fos, "UTF-8");</tt>

<P><tt><a href='http://java.sun.com/javase/6/docs/api/java/util/Scanner.html'>Scanner</a>
scanner = new Scanner(file, "UTF-8");</tt>


<P><b>Example 1</b><p>
Here is a fairly compact example (for JDK 1.5) of reading and writing a text file, using an explicit encoding. 
If you remove all references to encoding from this class, it will still work -- the system's default 
encoding will simply be used instead.
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> java.util.Scanner;

<span class='comment'>/** 
 Read and write a file using an explicit encoding.
 Removing the encoding from this code will simply cause the 
 system's default encoding to be used instead.  
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ReadWriteTextFileWithEncoding {

  <span class='comment'>/** Requires two arguments - the file name, and the encoding to use.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) <span class='keyword'>throws</span> IOException {
    String fileName = aArgs[<span class='literal'>0</span>];
    String encoding = aArgs[<span class='literal'>1</span>];
    ReadWriteTextFileWithEncoding test = <span class='keyword'>new</span> ReadWriteTextFileWithEncoding(
      fileName, encoding
    );
    test.write();
    test.read();
  }
  
  <span class='comment'>/** Constructor. */</span>
  ReadWriteTextFileWithEncoding(String aFileName, String aEncoding){
    fEncoding = aEncoding;
    fFileName = aFileName;
  }
  
  <span class='comment'>/** Write fixed content to the given file. */</span>
  <span class='keyword'>void</span> write() <span class='keyword'>throws</span> IOException  {
    log(<span class='literal'>"Writing to file named "</span> + fFileName + <span class='literal'>". Encoding: "</span> + fEncoding);
    Writer out = <span class='keyword'>new</span> OutputStreamWriter(<span class='keyword'>new</span> FileOutputStream(fFileName), fEncoding);
    <span class='keyword'>try</span> {
      out.write(FIXED_TEXT);
    }
    <span class='keyword'>finally</span> {
      out.close();
    }
  }
  
  <span class='comment'>/** Read the contents of the given file. */</span>
  <span class='keyword'>void</span> read() <span class='keyword'>throws</span> IOException {
    log(<span class='literal'>"Reading from file."</span>);
    StringBuilder text = <span class='keyword'>new</span> StringBuilder();
    String NL = System.getProperty(<span class='literal'>"line.separator"</span>);
    Scanner scanner = <span class='keyword'>new</span> Scanner(<span class='keyword'>new</span> FileInputStream(fFileName), fEncoding);
    <span class='keyword'>try</span> {
      <span class='keyword'>while</span> (scanner.hasNextLine()){
        text.append(scanner.nextLine() + NL);
      }
    }
    <span class='keyword'>finally</span>{
      scanner.close();
    }
    log(<span class='literal'>"Text read in: "</span> + text);
  }
  
  <span class='comment'>// PRIVATE 
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> String fFileName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fEncoding;
  <span class='keyword'>private</span> <span class='keyword'>final</span> String FIXED_TEXT = <span class='literal'>"But soft! what code in yonder program breaks?"</span>;
  
  <span class='keyword'>private</span> <span class='keyword'>void</span> log(String aMessage){
    System.out.println(aMessage);
  }
}
 
</PRE>
<br>

<br><b>Example 2</b><p>
This example uses <tt>FileReader</tt> and <tt>FileWriter</tt>, which implicitly use the system's default encoding.
To make this example compatible with JDK 1.4, just change <tt>StringBuilder</tt> to <tt>StringBuffer</tt>:
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;

<span class='keyword'>public</span> <span class='keyword'>class</span> ReadWriteTextFile {

  <span class='comment'>/**
  * Fetch the entire contents of a text file, and return it in a String.
  * This style of implementation does not throw Exceptions to the caller.
  *
  * @param aFile is a file which already exists and can be read.
  */</span>
  <span class='keyword'>static</span> <span class='keyword'>public</span> String getContents(File aFile) {
    <span class='comment'>//...checks on aFile are elided
</span>    StringBuilder contents = <span class='keyword'>new</span> StringBuilder();
    
    <span class='keyword'>try</span> {
      <span class='comment'>//use buffering, reading one line at a time
</span>      <span class='comment'>//FileReader always assumes default encoding is OK!
</span>      BufferedReader input =  <span class='keyword'>new</span> BufferedReader(<span class='keyword'>new</span> FileReader(aFile));
      <span class='keyword'>try</span> {
        String line = <span class='keyword'>null</span>; <span class='comment'>//not declared within while loop
</span>        <span class='comment'>/*
        * readLine is a bit quirky :
        * it returns the content of a line MINUS the newline.
        * it returns null only for the END of the stream.
        * it returns an empty String if two newlines appear in a row.
        */</span>
        <span class='keyword'>while</span> (( line = input.readLine()) != <span class='keyword'>null</span>){
          contents.append(line);
          contents.append(System.getProperty(<span class='literal'>"line.separator"</span>));
        }
      }
      <span class='keyword'>finally</span> {
        input.close();
      }
    }
    <span class='keyword'>catch</span> (IOException ex){
      ex.printStackTrace();
    }
    
    <span class='keyword'>return</span> contents.toString();
  }

  <span class='comment'>/**
  * Change the contents of text file in its entirety, overwriting any
  * existing text.
  *
  * This style of implementation throws all exceptions to the caller.
  *
  * @param aFile is an existing file which can be written to.
  * @throws IllegalArgumentException if param does not comply.
  * @throws FileNotFoundException if the file does not exist.
  * @throws IOException if problem encountered during write.
  */</span>
  <span class='keyword'>static</span> <span class='keyword'>public</span> <span class='keyword'>void</span> setContents(File aFile, String aContents)
                                 <span class='keyword'>throws</span> FileNotFoundException, IOException {
    <span class='keyword'>if</span> (aFile == <span class='keyword'>null</span>) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"File should not be null."</span>);
    }
    <span class='keyword'>if</span> (!aFile.exists()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> FileNotFoundException (<span class='literal'>"File does not exist: "</span> + aFile);
    }
    <span class='keyword'>if</span> (!aFile.isFile()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Should not be a directory: "</span> + aFile);
    }
    <span class='keyword'>if</span> (!aFile.canWrite()) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"File cannot be written: "</span> + aFile);
    }

    <span class='comment'>//use buffering
</span>    Writer output = <span class='keyword'>new</span> BufferedWriter(<span class='keyword'>new</span> FileWriter(aFile));
    <span class='keyword'>try</span> {
      <span class='comment'>//FileWriter always assumes default encoding is OK!
</span>      output.write( aContents );
    }
    <span class='keyword'>finally</span> {
      output.close();
    }
  }

  <span class='comment'>/** Simple test harness.   */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... aArguments) <span class='keyword'>throws</span> IOException {
    File testFile = <span class='keyword'>new</span> File(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;blah.txt"</span>);
    System.out.println(<span class='literal'>"Original file contents: "</span> + getContents(testFile));
    setContents(testFile, <span class='literal'>"The content of this file has been overwritten..."</span>);
    System.out.println(<span class='literal'>"New file contents: "</span> + getContents(testFile));
  }
} 
</PRE>
<br>

<br><a name='Example3'><b>Example 3</b><p>
This example demonstrates using 
<a href='http://java.sun.com/javase/6/docs/api/java/util/Scanner.html'>Scanner</a> to <em>read</em> a file containing lines of structured data.
Each line is then parsed using a second <tt>Scanner</tt> and a simple delimiter character, used to separate each line into a name-value pair.
The Scanner class is used only for reading, not for writing. 
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> java.util.Scanner;

<span class='keyword'>public</span> <span class='keyword'>class</span> ReadWithScanner {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs) <span class='keyword'>throws</span> FileNotFoundException {
    ReadWithScanner parser = <span class='keyword'>new</span> ReadWithScanner(<span class='literal'>"C:&#092;&#092;Temp&#092;&#092;test.txt"</span>);
    parser.processLineByLine();
    log(<span class='literal'>"Done."</span>);
  }
  
  <span class='comment'>/**
   Constructor.
   @param aFileName full name of an existing, readable file.
  */</span>
  <span class='keyword'>public</span> ReadWithScanner(String aFileName){
    fFile = <span class='keyword'>new</span> File(aFileName);  
  }
  
  <span class='comment'>/** Template method that calls {@link #processLine(String)}.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> processLineByLine() <span class='keyword'>throws</span> FileNotFoundException {
    <span class='comment'>//Note that FileReader is used, not File, since File is not Closeable
</span>    Scanner scanner = <span class='keyword'>new</span> Scanner(<span class='keyword'>new</span> FileReader(fFile));
    <span class='keyword'>try</span> {
      <span class='comment'>//first use a Scanner to get each line
</span>      <span class='keyword'>while</span> ( scanner.hasNextLine() ){
        processLine( scanner.nextLine() );
      }
    }
    <span class='keyword'>finally</span> {
      <span class='comment'>//ensure the underlying stream is always closed
</span>      <span class='comment'>//this only has any effect if the item passed to the Scanner
</span>      <span class='comment'>//constructor implements Closeable (which it does in this case).
</span>      scanner.close();
    }
  }
  
  <span class='comment'>/** 
   Overridable method for processing lines in different ways.
    
   &lt;P&gt;This simple default implementation expects simple name-value pairs, separated by an 
   '=' sign. Examples of valid input : 
   &lt;tt&gt;height = 167cm&lt;/tt&gt;
   &lt;tt&gt;mass =  65kg&lt;/tt&gt;
   &lt;tt&gt;disposition =  "grumpy"&lt;/tt&gt;
   &lt;tt&gt;this is the name = this is the value&lt;/tt&gt;
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> processLine(String aLine){
    <span class='comment'>//use a second Scanner to parse the content of each line 
</span>    Scanner scanner = <span class='keyword'>new</span> Scanner(aLine);
    scanner.useDelimiter(<span class='literal'>"="</span>);
    <span class='keyword'>if</span> ( scanner.hasNext() ){
      String name = scanner.next();
      String value = scanner.next();
      log(<span class='literal'>"Name is : "</span> + quote(name.trim()) + <span class='literal'>", and Value is : "</span> + quote(value.trim()) );
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"Empty or invalid line. Unable to process."</span>);
    }
    <span class='comment'>//no need to call scanner.close(), since the source is a String
</span>  }
  
  <span class='comment'>// PRIVATE 
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> File fFile;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(Object aObject){
    System.out.println(String.valueOf(aObject));
  }
  
  <span class='keyword'>private</span> String quote(String aText){
    String QUOTE = <span class='literal'>"'"</span>;
    <span class='keyword'>return</span> QUOTE + aText + QUOTE;
  }
} 
</PRE>
<br>
<br>Example run of this class :
<PRE>
Name is : 'height', and Value is : '167cm'
Name is : 'mass', and Value is : '65kg'
Name is : 'disposition', and Value is : '"grumpy"'
Name is : 'this is the name', and Value is : 'this is the value'
Done.
</PRE>

<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiona0d7-2.html?Id=8'>Always close streams</a> <br>
 
  
  <a href='TopicActioncc40-2.html?Id=87'>Parse text</a> <br>
 
  
  <a href='TopicAction23a3-2.html?Id=123'>Minimize ripple effects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='42'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=42 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
